import { emptyStyle, getStyle } from '../utils/style'
import { makeSetter } from '../utils'
const updateItems = (slot: any, colCount: any, rowCount: any) => {
  let cc = Number(colCount)
  let rc = Number(rowCount)
  const ids: string[] = []
  for (let r = 1; r <= rc; r++) {
    for (let c = 1; c <= cc; c++) {
      ids.push(`_${r}_${c}`)
    }
  }
  slot?.get?.()?.forEach?.((item: any) => {
    if (ids.includes(item.id)) return
    slot.remove(item.id)
  })
  for(const id of ids) {
    if(!slot.get(id)) {
      slot.add(id, `子项${id}`)
    }
  }
}
export default {
  '@init'({ style, data }) {
    style.height = 'auto'
    style.width = '100%'
    data.styleContent = emptyStyle
    data.style = {}
  },
  '@resize': {
    options: ['width', 'height']
  },
  ':root': ({ data, slot, env }: any, cate1, cate2, cate3) => {
    cate1.items = [
      {
        title: '列数',
        type: 'text',
        value: makeSetter('colCount', {
          convert(data, output, value) {
            console.log('date change', data,value)
            updateItems(slot, value, data.rowCount)
            return value
          }
        })
      },
      {
        title: '行数',
        type: 'text',
        value: makeSetter('rowCount', {
          convert(data, output, value) {
            updateItems(slot, data.colCount, value)
            return value
          }
        })
      }
    ]

    cate2.title = '样式'
    cate2.items = [
      {
        title: '',
        type: 'code',
        options: {
          language: 'css',
          enableFullscreen: false,
          title: '编辑校验规则',
          width: 600,
          minimap: {
            enabled: false
          },
          babel: true,
          eslint: {
            parserOptions: {
              ecmaVersion: '2020',
              sourceType: 'module'
            }
          }
        },
        value: makeSetter('styleContent', {
          convert(data, output, value) {
            let val = decodeURIComponent(value)
            let changed = false
            if (!val) {
              changed = true
              val = emptyStyle
            }
            if (!/^\s*:root\s*{/.test(val)) {
              changed = true
              val = emptyStyle
            }
            data.style = getStyle(val.trim() || '')
            if (changed) {
              return encodeURIComponent(val)
            }
            return value
          }
        })
      }
    ]
  }
}
